package com.zxy.day0624_util.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Base64;
import java.util.Random;
import sun.misc.BASE64Decoder;

/**
 * @Auther: lenovo
 * @Date: 2021/9/27 20:49
 * @Description:
 */
public class ImgAndBase64 {

    public ImgAndBase64() {
    }

    public static String ImgToBase64(InputStream inputStream) {
        InputStream is = inputStream;
        byte[] data = null;

        try {
            data = new byte[is.available()];
            is.read(data);
            is.close();
        } catch (IOException var4) {
            var4.printStackTrace();
        }

        return new String(Base64.getEncoder().encodeToString(data));
    }

    public static boolean Base64ToImg(String str) {
        if (str == null && str.length() == 0) {
            return false;
        } else {
            BASE64Decoder decoder = new BASE64Decoder();

            try {
                byte[] b = decoder.decodeBuffer(str);

                for(int i = 0; i < b.length; ++i) {
                    if (b[i] < 0) {
                        b[i] = (byte)(b[i] + 256);
                    }
                }

                String imgFilePath = "d://pic//imgAndBase64//" + (new Random()).nextInt(999999) + ".jpg";
                File file = new File(imgFilePath);
                if (!file.exists()) {
                    file.createNewFile();
                }

                System.err.println("图片地址为" + imgFilePath);
                FileOutputStream fileOutputStream = new FileOutputStream(imgFilePath);
                fileOutputStream.write(b);
                fileOutputStream.flush();
                fileOutputStream.close();
            } catch (IOException var6) {
                var6.printStackTrace();
            }

            return true;
        }
    }

    public static void main(String[] args) throws FileNotFoundException {
        File file = new File("D:\\QR_code\\test.jpg\\66913734.jpg");
        FileInputStream fileInputStream = new FileInputStream(file);
        String s = ImgToBase64(fileInputStream);
        System.out.println(s);
        boolean b = Base64ToImg(s);
        System.out.println(b);
    }
}
